<?php

namespace app\middleware;

use Closure;

use app\helpers\Common;
//use app\libs\Auth;
use app\facade\Auth;

use think\facade\Db;
use think\facade\Cache;

class AdminAuthenticate
{
    public function handle($request, Closure $next, $guard = null)
    {
        $guard = 'admin';
        if ($request->controller() == 'Auth') {
            return $next($request);
        }

        if (!Auth::guard($guard)) {
            if ($request->isAjax()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect((string)url('admin/auth/login'));
            }
        }

        if(!$this->authCheck($request, $guard)){
            //return redirect((string)url('admin/dashboard/index'))->with('error', '您没有访问权限！');
            return redirect((string)url('admin/errorpages/noauth'));
        }

        return $next($request);
    }

    /*
     * Check route auth
     */
    private function authCheck($request, $guard)
    {
        $guard = 'admin';
        $auth = Auth::guard($guard);
        $session_admin_id = $auth['id'];

        /*
        if (!empty($session_admin_id)) {
            if (!$this->checkAccess($request, $session_admin_id)) {
                return false;
            }
        }
        return true;
        */

        // 系统未做授权处理，故不需要验证权限授权 (checkAccess)
        // 0-超级管理员，不需要验证权限
        if ($auth['type'] == 0) {
            return true;
        }

        // 获取当前菜单
        $app = app('http')->getName();
        $pathinfo = explode('/', $request->pathinfo());
        $controller = !empty($pathinfo[0]) ? str_replace('.html', '', $pathinfo[0]) : 'index';
        $action = !empty($pathinfo[1]) ? str_replace('.html', '', $pathinfo[1]) : 'index';
        $uriArr = [$app, $controller, $action];
        $menuId = \app\common\model\AdminMenu::where('app', $uriArr[0])->where('controller', $uriArr[1])->where('action', $uriArr[2])->value('id');

        // 权限
        $roles = Db::name('admin_role_user')
            ->alias('a')
            ->join('admin_roles b', 'b.id = a.role_id')
            ->where('a.admin_id', $session_admin_id)
            ->field('a.role_id, b.access')
            ->select();

        $accessStr = '';
        foreach ($roles as $item) {
            $accessStr .= ',' . $item['access'];
        }
        $access = array_unique(explode(',', $accessStr));

        // 首页默认有权限
        if (in_array(strtolower($request->controller(true)), ['dashboard'])) {
            return true;
        }

        if (!in_array($menuId, $access)) {
            return false;
        }

        return true;
    }

    /**
     * 检查后台用户访问权限
     * @param int $adminId 后台用户id
     * @return boolean 检查通过返回true
     */
    private function checkAccess($request, $adminId)
    {
        $app = app('http')->getName();
        $pathinfo = explode('/', $request->pathinfo());
        $controller = !empty($pathinfo[0]) ? str_replace('.html', '', $pathinfo[0]) : 'index';
        $action = !empty($pathinfo[1]) ? str_replace('.html', '', $pathinfo[1]) : 'index';
        $uriArr = [$app, $controller, $action];

        $rule = $uriArr[0] . $uriArr[1] . $uriArr[2];
        $no_need_check_rules = array('admindashboardindex');

        if (!in_array($rule, $no_need_check_rules)) {
            return Common::checkAuth($request, $adminId);
        } else {
            return true;
        }
    }
}
